<template>
	<view class="files">
		<Navigation title="添加宠物" background="#fff" />
		<view class="f jc-c mt-40 w-f">
			<view class="w-160 h-160 head-box" @click="show=true">
				<image src="http://cwht.ricecs.cn/app/login/ava.png" class="w-160 h-160 headImg" v-show="!model.avatar">
				</image>
				<image :src="model.avatar" class="w-160 h-160 headImg" v-show="model.avatar"></image>
				<image src="http://cwht.ricecs.cn/app/login/edit.png" class="w-44 h-44 edit"></image>
			</view>
		</view>
		<view class="form mt-40 ph-40">
			<u--form labelPosition="left" :model="model" ref="formRef" labelWidth="80" :labelStyle="{ fontSize: 32 }"
				:rules="rules">
				<u-form-item label="昵称" prop="name" borderBottom>
					<u--input v-model="model.name" border="none" placeholder="请输入萌宠名字" fontSize="16"></u--input>
				</u-form-item>
				<u-form-item label="宠物类型" prop="firstCategoryId" borderBottom @click="showType = true">
					<view class="f jc-s-b">
						<u--input v-model="firstCategoryName" readonly disabledColor="#ffffff" placeholder="请选择萌宠类型"
							border="none"></u--input>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="宠物品种" prop="secondCategoryId" borderBottom @click="showBreed = true"/>
				<!-- <u-form-item label="宠物品种" prop="secondCategoryId" borderBottom @click="gopetBreeds()">
					<view class="f jc-s-b">
						<u--input v-model="secondCategoryCodeName" readonly disabledColor="#ffffff"
							placeholder="请选择萌宠种类" border="none"></u--input>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item> -->
				<u-form-item label="宠物性别" prop="gender" borderBottom @click="showSex = true">
					<view class="f jc-s-b">
						<u--input v-model="genderName" readonly disabledColor="#ffffff" placeholder="请选择萌宠性别"
							border="none"></u--input>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="出生日期" prop="birthday" borderBottom @click="showBirthday = true">
					<view class="f jc-s-b">
						<u--input v-model="birthday" readonly disabledColor="#ffffff" placeholder="请选择年/月/日"
							border="none"></u--input>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item>

				<u-form-item label="是否绝育" prop="sterilization" borderBottom @click="showSterilization = true">
					<view class="f jc-s-b">
						<u--input v-model="sterilizationName" readonly disabledColor="#ffffff" placeholder="请选择"
							border="none"></u--input>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<view class="w-f h-136 f ph-40 bot-box pv-20 jc-s-b ai-c">
			<view @click="reset">
				<image src="http://cwht.ricecs.cn/app/login/reset.png" class="w-40 h-40"></image>
				<view class="fs-24 text-color1">重置</view>
			</view>
			<view class="w-558"><u-button text="确定" color="#FABB3C" shape="circle" @click="submit"></u-button> </view>
		</view>
		<!-- 类型 -->
		<u-action-sheet :show="showType" :actions="typeList" title="请选择类型" @close="showType = false"
			@select="typeSelect"> </u-action-sheet>
		<!-- 品种 -->
		<!-- <u-action-sheet :show="showBreed" :actions="breedList" title="请选择品种" @close="showBreed = false"
			@select="breedSelect"> </u-action-sheet> -->
		<!-- 出生日期 -->
		<u-datetime-picker ref="datetimePicker" :show="showBirthday" v-model="model.birthday" mode="date"
			@confirm="selectBirthday" @close="showBirthday = false" :formatter="formatter"></u-datetime-picker>
		<!-- 性别 -->
		<u-action-sheet :show="showSex" :actions="sexList" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>

		<!-- 是否绝育 -->
		<u-action-sheet :show="showSterilization" :actions="sterilizationList" title="请选择是否绝育"
			@close="showSterilization = false" @select="sterilizationSelect" @cancel="showSterilization = false">
		</u-action-sheet>
		<qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop" v-if="show"  @close="show=false"></qf-image-cropper>
	</view>
</template>
<script setup lang="ts">
	import { ref, getCurrentInstance, watch } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { getUploadUrl } from '@/utils/env';
	import { categorySimpleQuery, petCreate, petUpdate, mypetProfileDetail } from '@/services/api/pet';
	import { throttle, isNullorEmpty } from '@/utils/global';
	const { proxy } = getCurrentInstance();
	const showType = ref(false);
	// const showBreed = ref(false);
	const showBirthday = ref(false);
	const showSex = ref(false);
	const showSterilization = ref(false);
	const show = ref(false)
	const typeList = ref<any[]>([]);
	const breedList = ref<any[]>([]);
	const sexList = ref([
		{ name: '雄', id: 1 },
		{ name: '雌', id: 2 },
		{ name: '未知', id: 3 },
	]);
	const sterilizationList = ref([
		{ name: '是', id: 0 },
		{ name: '否', id: 1 },
	]);
	const model = ref<any>({
		id: null,
		avatar: null,
		name: null,
		firstCategoryId: null,
		secondCategoryId: null,
		gender: null,
		birthday: null,
		sterilization: null,
	});
	const firstCategoryName = ref('');
	const secondCategoryCodeName = ref('');
	const genderName = ref('');
	const birthday = ref('');
	const sterilizationName = ref('');
	const type = ref(''); //新用户
	const rules = {
		name: [
			{
				required: true,
				message: '不能为空',
				trigger: ['blur', 'change'],
			},
		],
		firstCategoryId: [
			{
				required: true,
				message: '不能为空',
				transform(value : string) {
					return String(value);
				},
				trigger: ['blur', 'change'],
			},
		],
		secondCategoryId: [
			{
				required: true,
				message: '不能为空',
				transform(value : string) {
					return String(value);
				},
				trigger: ['blur', 'change'],
			},
		],
		gender: [
			{
				required: true,
				message: '不能为空',
				transform(value : string) {
					return String(value);
				},
				trigger: ['blur', 'change'],
			},
		],
		birthday: [
			{
				required: true,
				message: '不能为空',
				transform(value : string) {
					return String(value);
				},
				trigger: ['blur', 'change'],
			},
		],
		sterilization: [
			{
				required: true,
				message: '不能为空',
				transform(value : string) {
					return String(value);
				},
				trigger: ['blur', 'change'],
			},
		],
	};
	onLoad((options : any) => {
		if (options.id) {
			model.value.id = options.id;
			// getBreed();
			getDetail();
		} else {
			getCategory();
		}
		if (options.type) {
			type.value = options.type;
		}
	});
	onShow(() => {
		uni.$on('updateNote', function (data) {
			secondCategoryCodeName.value = data.name;
			model.value.secondCategoryId = data.id
		})
	});
	watch(
		firstCategoryName,
		() => {
			// getBreed();
		},
		{ immediate: true }
	);
	//获取详情
	async function getDetail() {
		const { data } = await mypetProfileDetail(model.value.id);
		data.birthday = data.birthday.join('-');
		for (let key in model.value) {
			model.value[key] = data[key];
		}
		const category = await categorySimpleQuery({ parentId: 0 });
		typeList.value = category.data;
		if (model.value.firstCategoryId) {
			const secondCategory = await categorySimpleQuery({ parentId: model.value.firstCategoryId });
			breedList.value = secondCategory.data;
		}
		secondCategoryCodeName.value = data.secondCategoryName;
		firstCategoryName.value = data.firstCategoryName;
		if (data.gender == 1) {
			genderName.value = '雄';
		} else if (data.gender == 2) {
			genderName.value = '雌';
		} else {
			genderName.value = '未知';
		}
		birthday.value = data.birthday;
		sterilizationName.value = data.sterilization == 0 ? '是' : '否';
	}
	function handleCrop(e) {
		uploadFiles(e.tempFilePath);
	}
	//提交
	const submit = throttle(() => {
		submitData();
	}, 1000);
	async function submitData() {
		// console.log(model.value);
		if (!model.value.avatar) {
			uni.showToast({
				title: '请上传头像',
				icon: 'none',
			});
			return;
		}
		model.value.birthday = uni.$u.timeFormat(model.value.birthday);
		proxy.$refs.formRef.validate().then(async () => {
			if (model.value.id) {
				await petUpdate(model.value);
				uni.showToast({
					title: '修改成功',
					icon: 'none',
				});
			} else {
				await petCreate(model.value);
				uni.showToast({
					title: '保存成功',
					icon: 'none',
				});
			}
			if (type.value == 'new') {
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}, 1000);
			} else {
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			}
		});
	}
	//选择是否绝育
	function sterilizationSelect(e : any) {
		model.value.sterilization = e.id;
		sterilizationName.value = e.name;
	}
	function formatter(type : string, value : string) {
		if (type === 'year') {
			return `${value}年`;
		}
		if (type === 'month') {
			return `${value}月`;
		}
		if (type === 'day') {
			return `${value}日`;
		}
		return value;
	}
	//选择日期
	function selectBirthday(e : any) {
		let data = uni.$u.timeFormat(e.value);
		birthday.value = data;
		model.value.birthday = data;
		showBirthday.value = false;
		console.log(model.value);
	}
	//选择性别
	function sexSelect(e : any) {
		genderName.value = e.name;
		model.value.gender = e.id;
	}
	//选择品种
	// function breedSelect(e : any) {
	// 	secondCategoryCodeName.value = e.name;
	// 	model.value.secondCategoryId = e.id;
	// }
	//选择类型
	function typeSelect(e : any) {
		firstCategoryName.value = e.name;
		model.value.firstCategoryId = e.id;
		model.value.secondCategoryId = '';
		secondCategoryCodeName.value = '';
		breedList.value = [];
		// getBreed()
	}
	//去宠物品种
	function gopetBreeds() {
		if (!isNullorEmpty(model.value.firstCategoryId)) {
			uni.navigateTo({
				url: `/pages_mine/petBreeds?id=${model.value.firstCategoryId}`
			});
		} else {
			uni.showToast({
				title: '请先选择宠物类型',
				icon: 'none',
			});
		}
	}
	//获取品种
	// async function getBreed() {
	// 	const { data } = await categorySimpleQuery({ parentId: model.value.firstCategoryId });
	// 	breedList.value = data;
	// }
	//获取类型
	async function getCategory() {
		const { data } = await categorySimpleQuery({ parentId: 0 });
		typeList.value = data;
	}
	//上传
	function upload() {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: function (res : any) {
				uploadFiles(res.tempFilePaths[0]);
			},
		});
	}
	function uploadFiles(url : string) {
		uni.uploadFile({
			url: getUploadUrl(),
			filePath: url,
			name: 'file',
			formData: {},
			success: (res : any) => {
				console.log(res);
				let data = JSON.parse(res.data);
				model.value.avatar = data.data;
				show.value = false
			},
		});
	}
	// function toNext() {
	//     uni.navigateTo({
	//         url: '/pages_login/wantToRaise',
	//     });
	// }
	//重置
	function reset() {
		model.value = {
			id: null,
			avatar: null,
			name: null,
			firstCategoryId: null,
			secondCategoryId: null,
			gender: null,
			birthday: null,
			sterilization: null,
		};
		firstCategoryName.value = '';
		genderName.value = '';
		birthday.value = '';
		sterilizationName.value = '';
		sterilizationName.value = '';
		secondCategoryCodeName.value = '';
	}
</script>
<style lang="scss" scoped>
	.files {
		width: 100%;
		min-height: 100vh;
		background: #f5f5f5;

		.bot-box {
			background: #fff;
			position: fixed;
			left: 0;
			bottom: 0;

			::v-deep .u-button {
				height: 96rpx !important;
			}
		}

		.form {
			background: #fff;
		}

		.head-box {
			position: relative;

			.edit {
				position: absolute;
				right: 0;
				bottom: 0;
			}

			.headImg {
				border-radius: 50%;
			}
		}

		::v-deep .u-form-item__body {
			padding: 32rpx 0 !important;
		}
	}
</style>